import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { Observable, throwError, Subject } from 'rxjs'
import { ServerRequest } from 'http'
import { SERVER_URL } from 'app/utils/contraints'
import { generateOptions } from 'app/utils/helpers'
import { catchError, map } from 'rxjs/operators'
import { ObservableStore } from '@shared/classes/ObservableStoreClass'
import { Merchant } from '@shared/interfaces/merchant'

@Injectable({
  providedIn: 'root'
})
export class CommonMerchantService {

  private defaultParams = {
    keyword: '',
    limit: 100,
  }

  merchant$ = new Subject<any[]>()

  viewingMerchant$ = new ObservableStore(new Merchant())

  constructor(
    private http: HttpClient,
  ) {}

  setViewingMerchant(merchant: Merchant) {
    this.viewingMerchant$.setValue(merchant)
  }

  get viewingMerchant() {
    return this.viewingMerchant$.value
  }

  queryMerchants(params = this.defaultParams, filterMap = {}): Observable<any> {
    const url = `${SERVER_URL}/list`
    const options = generateOptions(params)

    const body = {
      codeField: 'storeNum',
      colName: 'store',
      filterMap,
      nameField: 'storeDetail.storeName',
    }

    return this.http.post<any>(url, body, options).pipe(
      map(res => {
        return this.trans(res)
      }),
      catchError(err => throwError(err))
    )
  }

  private trans(arrs: any): any {
    return arrs.map(a => {
      return { localName: a.name, label: a.name + '  ' + a.code, value: a.code }
    })
  }
}
